#define _CRT_SECURE_NO_WARNINGS 1
#include"Slist.h"

SL* CreatSLTNode(SLTDataType x)
{
	SL* newnode = (SL*)malloc(sizeof(SL));
	if (newnode == NULL)
	{
		printf("malloc failed\n");
		return;
	}
	newnode->Data = x;
	newnode->next = NULL;
	return newnode;
}

void SLTPushBack(SL** PPhead, SLTDataType x)
{
	SL* newnode = CreatSLTNode(x);
	if (*PPhead == NULL)
	{
		*PPhead = newnode;
	}
	else
	{
		SL* tail = *PPhead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLTPrint(SL* Phead)
{
	while (Phead != NULL)
	{
		printf("%d ", Phead->Data);
		Phead = Phead->next;
	}
}

void SLTPushFront(SL** PPhead, SLTDataType x)
{
	SL* newnode = CreatSLTNode(x);
	newnode->next = *PPhead;
	*PPhead = newnode;
}

void SLTPopFront(SL** PPhead)
{
	SL* next = (*PPhead)->next;
	free(*PPhead);
	*PPhead = next;
}

void SLTPopBack(SL** PPhead)
{
	if (*PPhead == NULL)
	{
		return;
	}
	else if ((*PPhead)->next == NULL)
	{
		free(*PPhead);
		*PPhead = NULL;
	}
	else
	{
		SL* prev = NULL;
		SL* tail = *PPhead;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next = NULL;
	}
}

SL* SLTFindData(SL* Phead, SLTDataType x)
{
	SL* cur = Phead;
	while (cur != NULL)
	{
		if (cur->Data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsert(SL** PPhead, SL* pos, SLTDataType x)
{
	if (pos == *PPhead)
	{
		SLTPushFront(PPhead, x);
	}
	else
	{
		SL* newnode = CreatSLTNode(x);
		SL* prev = *PPhead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}

void SLTErase(SL** PPhead, SL* pos)
{
	if (pos == *PPhead)
	{
		SLTPopFront(PPhead);
	}
	else
	{
		SL* prev = *PPhead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}